package araxy.blog.utils;

import araxy.blog.EnvironmentCheck;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
import org.eclipse.jgit.transport.CredentialsProvider;
import org.eclipse.jgit.transport.URIish;

import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class GitUtil {

    private static Git git;
    private static CredentialsProvider credentialsProvider;

    public static void init(String repoPath,String remoteUrl) throws GitAPIException, IOException, URISyntaxException {
        credentialsProvider = SpringContextsUtil.getBean(CredentialsProvider.class);

        Path dotGit = Paths.get(repoPath,".git");
        if (Files.exists(dotGit)) {
            git = Git.open(dotGit.toFile());
            return;
        }
        Path gitRoot = Paths.get(repoPath);
        if (!Files.exists(gitRoot)) {
            Files.createDirectories(gitRoot);
        }
        git = Git.init().setDirectory(gitRoot.toFile()).call();
        git.remoteAdd().setUri(new URIish(remoteUrl)).setName("origin").call();
        commitAll(DateUtil.getSysTime("yyyy-MM-dd"));
        push();
    }

    public static void push() throws GitAPIException {
        git.push().setCredentialsProvider(credentialsProvider).call();
    }

    public static void pull() throws GitAPIException {
        git.pull().setCredentialsProvider(credentialsProvider).call();
    }

    public static void commitAll(String commitMsg) throws GitAPIException {
        commit(commitMsg,".");
    }

    public static void commit(String commitMsg,String filePattern) throws GitAPIException {
        git.add().addFilepattern(filePattern).call();
        git.commit().setMessage(commitMsg).call();
    }

}
